<template>
  <div id="pdfDom">
    <el-row>
      <el-col :span="12">
        <div class="canvas">
          <!-- <video ref="video" width="600" height="400" autoplay="autoplay"></video> -->
          <iframe ref="iframe" frameborder="0" name="showHere" src="/html/media.html"></iframe>
          <!-- <canvas ref="canvas" width="600" height="400"></canvas> -->
        </div>
      </el-col>
      <el-col :span="12">
        <el-form ref="form" label-width="200px" :model="form">
          <el-form-item label="车牌号">
            <el-input v-model="form.catID" placeholder="请输入车牌号"></el-input>
          </el-form-item>
          <el-form-item label="原车主头像" :span="12">
            <el-image
              :src="form.headImg"
              fit="contain"
              class="img"
              :preview-src-list="[form.headImg]"
            >
              <div slot="error">没上传</div>
            </el-image>
            <div>
              <el-upload
                style="float:left;margin-right: 10px"
                :action="$http.defaults.baseURL + 'upload'"
                :show-file-list="false"
                :on-success="handleHeadImgSuccess"
                :headers="token"
              >
                <el-button size="small">上传</el-button>
              </el-upload>
              <el-button type="primary" size="small" @click="takePhoto">拍照</el-button>
            </div>
          </el-form-item>
          <el-form-item label="卖家指纹" :span="12">
            <el-image :src="form.fgpImg" class="img" fit="contain" :preview="form.fgpImg">
              <div slot="error">没上传</div>
            </el-image>
            <div>
              <el-upload
                style="float:left;margin-right: 10px"
                :action="$http.defaults.baseURL + 'upload'"
                :show-file-list="false"
                :on-success="handleFgpSuccess"
                :headers="token"
              >
                <el-button size="small">上传</el-button>
              </el-upload>
              <el-button type="primary" size="small">获取指纹</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <div class="flex-centent">
      <el-button type="primary" size="small" @click="addPreview">确认书打印预览</el-button>
      <el-button type="info" size="small" @click="stopMedia">下一步</el-button>
      <el-button v-if="edit" type="warning" size="small" @click="putCat">修改</el-button>
    </div>

    <!-- 确认书打印预览 -->
    <el-dialog title="确认书打印预览" :visible.sync="Confirmation" width="1000px">
      <div class="flex-centent">
        <el-button type="primary" v-print="'#printDiv'">打 印</el-button>
        <el-button type="danger" @click="Confirmation=false">关 闭</el-button>
      </div>
      <br />
      <pdfDom id="printDiv" :user="form"></pdfDom>
    </el-dialog>
  </div>
</template>

<script>
let MediaStreamTrack;
import { dataURLtoBlob, blobToFile } from "../../unit";
import pdfDom from "../../components/pdf"; //打印模板
export default {
  beforeRouteEnter(to, form, next) {
    next();
  },
  beforeRouteLeave(to, form, next) {
    MediaStreamTrack &&
      MediaStreamTrack.forEach(t => {
        t.stop();
      });
    next();
  },
  components: { pdfDom },
  props: {
    id: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      options: [],
      form: {
        catID: "",
        headImg: "",
        fgpImg: ""
      },
      preview: false,
      Confirmation: false,
      edit: false,
      token: { Authorization: `Bearer ${sessionStorage.getItem("token")}` }
    };
  },
  created() {
    this.id && this.getCat();
  },
  mounted() {
    // 获取摄像头
    // this.getMedia();
  },
  methods: {
    // 新增并预览
    async addPreview() {
      //有指纹之后做判断
      if (!this.form.catID || !this.form.headImg) {
        this.$message({
          message: "请填完整",
          type: "warning"
        });
        return false;
      }
      let info = "";
      if (!this.id && !this.form._id) {
        let date = new Date();
        let y = date.getFullYear();
        let m = date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth();
        let d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        let num =
          String(y) +
          String(m) +
          String(d) +
          Number(new Date())
            .toString()
            .slice(5, -3) +
          Math.floor(Math.random() * 1000);
        console.log("tag", num);
        info = await this.$http.post(
          `/cats`,
          Object.assign({ fID: num }, this.form)
        );
        try {
          this.form = info.data;
        } catch (e) {
          console.log("获取id失败:" + e);
        }
      } else {
        this.putCat();
      }
      if (this.id || this.form._id) {
        this.Confirmation = true;
        this.preview = true;
      }
    },
    // 修改
    async putCat() {
      //有指纹之后做判断
      if (!this.form.catID || !this.form.headImg) {
        this.$message({
          message: "请填完整",
          type: "warning"
        });
        return false;
      }

      try {
        await this.$http.put("/cats", this.form);
        if (!this.preview) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
        }
        this.preview = true;
      } catch (e) {
        this.$message.error("错了哦" + e);
      }
    },
    //获取数据
    async getCat() {
      const forms = await this.$http.get(`/cats/${this.id}`);
      try {
        this.form = forms.data;
      } catch (e) {
        console.log("err", e);
      }
    },

    // 头像
    handleHeadImgSuccess(res) {
      console.log("res", res);
      // this.model.imageUrl = URL.createObjectURL(file.raw);
      this.$set(this.form, "headImg", res.url);
    },
    // 指纹
    handleFgpSuccess(res) {
      // this.model.imageUrl = URL.createObjectURL(file.raw);
      this.$set(this.form, "fgpImg", res.url);
    },
    async takePhoto() {
      var iframe = this.$refs.iframe;
      var iwindow = iframe.contentWindow;
      let src = iwindow.proof();
      // var idoc = iwindow.document;
      // var canvas = idoc.getElementById("canvas");
      // console.log('ca', src)
      //获得Canvas对象
      // let video = this.$refs.video;
      // let canvas = this.$refs.canvas;
      // let ctx = canvas.getContext("2d");
      // ctx.drawImage(video, 0, 0, 600, 400);
      // let src = canvas.toDataURL("image/png");

      var blob = dataURLtoBlob(src);
      var file = blobToFile(blob);
      let forms = new FormData();
      forms.append("file", file);
      let img = await this.$http.post("upload", forms);
      this.$set(this.form, "headImg", img.data.url);
    },
    stopMedia() {
      if (!this.form._id) {
        this.$message({
          message: "请预览",
          type: "warning"
        });
        return;
      }
      this.$router.push(`/media/index1/${this.form._id}`);
      MediaStreamTrack &&
        MediaStreamTrack.forEach(t => {
          t.stop();
        });
    }
  },
  watch: {
    form(newValue) {
      if ((this.id || this.form._id) && newValue) {
        this.edit = true;
      }
    }
  }
};
</script>

<style lang="scss">
.canvas {
  position: relative;
  width: 600px;
  height: 400px;
  overflow: hidden;
  iframe {
    width: 100%;
    height: 100%;
  }
}
.img {
  width: 200px;
  height: 200px;
  background-color: #f2f6fc;
}
</style>